/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.download.lib;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 *
 * @author 尹俊博
 */
public class HttpDownload {
       private static String URL_PATH;
 
    public HttpDownload(String in,String out) {
        URL_PATH = in;
        saveToDisk(out);
        // TODO Auto-generated constructor stub
    }
 
    public static void saveToDisk(String OUT_PATH) {
        // 获取输入流
        InputStream inputStream = getInputStream();
 
        byte[] date = new byte[1024];
        int len = 0;
        FileOutputStream fileOutputStream = null;
 
        try {
            fileOutputStream = new FileOutputStream(OUT_PATH);
 
            while ((len = inputStream.read(date)) != -1) {
                fileOutputStream.write(date, 0, len);
 
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
 
            try {
                if (inputStream != null) {
                    inputStream.close();
 
                }
 
                if (fileOutputStream != null) {
                    fileOutputStream.close();
 
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
 
        }
 
    }
 
    /**
     * @return
     */
    public static InputStream getInputStream() {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
 
        try {
            URL url = new URL(URL_PATH);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            // 设置连接网络的超时时间
            httpURLConnection.setConnectTimeout(3000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("GET");
 
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {
                inputStream = httpURLConnection.getInputStream();
 
            }
 
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 
        return inputStream;
    }
 

}
